<template>
	<view
		class="chat-container"
		:style="currentMessages.length ? { background: 'linear-gradient(to top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0,0.01))' } : { background: 'transparent' }"
	>
		<!-- 无数据时透明背景 -->
		<!-- 有数据才显示滚动区和弹幕，无数据直接隐藏 -->
		<scroll-view v-if="currentMessages.length" class="chat-scroll" :style="{ width: windowWidth }" scroll-y="true" :scroll-top="lastScrollTop">
			<view class="reverse-wrapper">
				<!-- 消息列表 -->
				<view v-for="(msg, index) in currentMessages" :key="msg.timestamp || index" class="message-item-outer">
					<view class="message-row" :style="{alignItems:'flex-end'}">
						<image class="avatar" v-if="msg.nicPic.url" :src="msg.nicPic.url || '/static/default-avatar.png'" mode="aspectFill"></image>
						<avatar-fallback v-else :name="msg.nicName" :size="20"></avatar-fallback>
						<text class="nickname">{{ msg.nicName || '匿名用户' }}:</text>
						<view class="meta">
							<text class="time">{{ formatMessageTime(msg.timestamp) }}</text>
							<text class="distance">{{ distance(msg) }}</text>
						</view>
					</view>

					<view class="map-content-group">
						<text class="map-message-text" lines=0>{{ getMessageContent(msg) }}</text>
					
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 始终显示加入栏/输入框（无数据时唯一可见元素） -->
		<view v-if="!isFavorite" class="join" @click.stop="join">
			<text class="joni-text">加入</text>
		</view>
		<linli-input v-else></linli-input>

		<!-- 有数据才显示弹幕，无数据隐藏 -->
		<Danmaku v-if="currentMessages.length"></Danmaku>
	</view>
</template>

<script>
// 脚本部分无修改，保持原有逻辑
import formatMessageTime from '../utils/formatMessageTime';
import chatFromStore from '../utils/chatFromStore';
import { formatDistance, distanceNum } from '../utils/distance';
import ChatPagination from '@/utils/chatPagination';
import newMsgAction from '@/utils/newMsgAction';
import Danmaku from './Danmaku.vue';
import linliInput from './linliInput.vue';
import Favorite from '../utils/favoriteClass';
import AvatarFallback from './AvatarFallback.vue';
import getFriendUserInfo from '../utils/getFriendUserInfo';

export default {
	components: {
		Danmaku,
		linliInput,
		AvatarFallback
	},
	data() {
		return {
			noticList: [],
			pagination: null,
			windowWidth: 0,
			isLoading: false,
			hasMore: true,
			lastScrollTop: 9999,
			keyboardHeight: false,
			isFavorite: false,
			userInfoCache: {}
		};
	},
	computed: {
		publicMessageList() {
			return this.$store.state.msg.publicMessageList || [];
		},
		currentMessages() {
			const msgs = this.pagination?.currentMessages || [];
			const cache = this.userInfoCache;
			return msgs.map((msg) => {
				const userId = msg.sendUserId;
				if (userId === this.storeData.user.userId) {
					return {
						...msg
					};
				}

				const userInfo = cache[userId] || {};
				return {
					...msg,
					nicName: userInfo.nicName || '匿名',
					nicPic: userInfo.nicPic || ''
				};
			});
		},
		currentPage() {
			return this.pagination?.currentPage || 1;
		},
		storeData() {
			return this.$store.state.msg;
		},
		favos() {
			return this.$store.state.msg.user.favorite;
		},
		currentTimeMsg() {
			const newMsg = this.$store.state.msg.newMessage || {};
			if (Object.keys(newMsg).length > 0) {
				const isNewMsg = newMsgAction(newMsg, this.$store.state.msg.queryParam);
				return isNewMsg.code ? isNewMsg.msg : {};
			}
			return {};
		},
		location() {
			return this.$store.state.msg.location;
		}
	},
	watch: {
		'pagination.currentMessages': {
			handler: async function (newMessages) {
				try {
					if (!newMessages || newMessages.length === 0) {
						this.userInfoCache = {};
						return;
					}
					const tempCache = { ...this.userInfoCache };
					const userIdsToFetch = new Set();
					newMessages.forEach((msg) => {
						const userId = msg.sendUserId;
						if (userId && userId !== this.storeData.user.userId && !tempCache[userId]) {
							userIdsToFetch.add(userId);
						}
					});
					if (userIdsToFetch.size > 0) {
						const fetchPromises = Array.from(userIdsToFetch).map((id) => getFriendUserInfo(id, this.storeData.user.userId));

						const results = await Promise.all(fetchPromises);
						results.forEach((info) => {
							if (info.userId) {
								tempCache[info.userId] = info;
							}
						});
					}
					this.userInfoCache = tempCache;
				} catch (e) {
					console.error(e);
				}
			},
			immediate: true,
			deep: true
		},
		currentTimeMsg: {
			handler(newTimeMsg) {
				if (!this.pagination) return; // 兜底：避免pagination未初始化
				if (!newTimeMsg || Object.keys(newTimeMsg).length === 0) return;
				this.$nextTick(() => {
					this.lastScrollTop = this.lastScrollTop + 500;
				});

				const index = this.publicMessageList.findIndex((item) => item.timestamp === newTimeMsg.timestamp);
				let messageList = [];

				if (index === -1) {
					messageList = [...this.publicMessageList, newTimeMsg];
					this.$store.commit('msg/SET_publicMessageList', messageList);
				} else {
					messageList = [...this.publicMessageList];
					messageList[index] = newTimeMsg;
					this.$store.commit('msg/SET_publicMessageList', messageList);
				}

				this.pagination.resetWithNewMessages(messageList);
			},
			deep: true,
			immediate: false
		},
		location: {
			handler(newval, oldval) {
				if (distanceNum(newval, oldval) > 100) {
					this.initData();
				}
			}
		}
	},
	mounted() {
		this.initData();
		this.getIsFavorite();
		uni.$on('keyHightEvent', (res) => {
			// 仅保留滚动位置更新，不重建pagination
		});
		const res = uni.getSystemInfoSync();
		this.windowWidth = res.windowWidth;
	},
	destroyed() {
		uni.$off('keyHightEvent');
	},
	methods: {
		formatMessageTime,
		isShowMeta(msg) {},
		async getIsFavorite() {
			try {
				const favorite = new Favorite(this.storeData.location, this.storeData);
				const res = await favorite.isFavorited(this.storeData.location);
				this.isFavorite = res.code;
			} catch (e) {
				console.error(e);
			}
		},
		getMessageContent(msg) {
			switch (msg.messageType) {
				case 2:
					return msg.content.text || '';
				case 1:
					return '发送了语音信息';
				case 3:
					return '发送了图片信息';
				case 4:
					return '发送了商品信息';
				case 5:
					return '发送了视频信息';
				default:
					return '';
			}
		},
		distance(item) {
			return formatDistance(this.storeData.senderLocation, item);
		},
		async initData() {
			this.$store.commit('msg/SET_publicMessageList', []);
			const queryParam = this.$store.state.msg.queryParam;

			if (queryParam.type === 'stranger') return;

			if (!this.pagination) {
				this.pagination = new ChatPagination([], 15);
			}

			try {
				this.isLoading = true;
				const viewlist = await chatFromStore(queryParam, this.storeData.user);
				this.$store.commit('msg/SET_publicMessageList', viewlist);
				await this.pagination.resetWithNewMessages(viewlist);
			} catch (e) {
				console.error('加载消息失败：', e);
				uni.showToast({ title: '加载消息失败', icon: 'fail' });
			} finally {
				this.isLoading = false;
			}
		},
		async join() {
			try {
				const favo = new Favorite(this.storeData.location, this.storeData);
				const res = await favo.add(this.storeData.location, this.storeData.address);
				if (res.code) {
					this.isFavorite = true;
					this.$store.commit('msg/SET_user', { ...this.$store.state.msg.user, favorite: [...res.data.favorite] });
					this.$emit('reLoadData');
					uni.showToast({ title: '加入成功', position: 'center' });
				} else {
					uni.showToast({ title: res.msg, icon: 'error' });
				}
			} catch (e) {
				console.error(e);
			}
		},
		async loadMoreMessages() {
			if (!this.pagination || this.isLoading || !this.hasMore) return;
			this.isLoading = true;
			this.hasMore = await this.pagination.loadMoreHistory();
			this.isLoading = false;
		}
	}
};
</script>

<style lang="scss" scoped>
/* 容器固定宽度，无数据时仅由子元素决定高度 */
.chat-container {
	position: fixed;
	left: 0;
	bottom: 80rpx;
	height: 500rpx;
	z-index: 200;
	/* 移除固定高度，避免无数据时占位 */
}
.message-item-outer {
	margin-bottom: 20rpx; // 保留间距
}

/* 加入栏：保持原有样式，确保无数据时仅显示这部分 */
.join {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 1500;
	width: 750rpx;
	height: 100rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #55aaff;
	border-radius: 16rpx;
}
.joni-text {
	font-size: 28rpx;
	color: #fff;
	font-weight: 600;
}
/* 有数据时才显示滚动区，保留原有样式 */
.chat-scroll {
	height: 500rpx;
	padding: 20rpx;

	position: relative;
	margin-bottom: 110rpx; /* 给输入框/加入栏留空间，避免遮挡 */
}
/* 其他样式保持不变 */
.message-row {
	display: flex;
	align-items: flex-end;
	flex-direction: row;
	padding: 10rpx 15rpx;


}
.map-avatar-container {
	width: 40rpx;
	margin-right: 10rpx;
}

.avatar {
	width: 40rpx;
	height: 40rpx;
	border-radius: 20rpx;
}

.map-content-group {
	min-width: 200;
	max-width: 500rpx;
    margin-left: 50rpx;
	padding: 10rpx;
	border-radius: 20rpx;
	background-color: rgba(0, 0, 0, 0.2);

}

.nickname {
	font-size: 28rpx;
	color: #00ffff;
	font-weight: 600;
	margin-right: 5rpx;
}

.map-message-text {
	font-size: 26rpx;
	color: #fff;
	font-weight: 600;

}

.meta {
	display: flex;
	flex-direction: row;
	margin-bottom: 5rpx;
}

.time {
	font-size: 20rpx;
	color: #ffffff;
	margin-left: 5rpx;
}

.distance {
	font-size: 20rpx;
	color: #ffffff;
	margin-left: 5rpx;
}
</style>
